﻿using MockJson.Database;
using Nancy.Hosting.Self;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Windows.Forms;

namespace MockJson
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            InitializeListView();
            ReLoadApi();
            InitializeServerConfig();
        }

        string IP = "";
        string PORT = "";
        private void InitializeServerConfig()
        {
            LoadUrl();
            var autoStart = App.GetValue("AUTOSTART", "0", null);
            if (autoStart == "1")
            {
                btnStart_Click(null, null);
            }
        }

        NancyHost _nancyHost;
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                var text = btnStart.Tag.ToString();
                if (text == "NowStop")
                {
                    var url = new Nancy.Url($"http://{IP}:{PORT}");
                    var hostConfig = new HostConfiguration
                    {
                        UrlReservations = new UrlReservations { CreateAutomatically = true }
                    };
                    _nancyHost = new NancyHost(hostConfig, url);

                    _nancyHost.Start();
                    btnStart.Text = "已启动";
                    btnStart.Tag = "NowStart";
                    btnStart.BackColor = Color.MediumSeaGreen;
                    lblStatus.Text = url.ToString();
                    lblStatus.ForeColor = Color.MediumSeaGreen;
                }
                else
                {
                    _nancyHost.Stop();
                    btnStart.Text = "已停止";
                    btnStart.Tag = "NowStop";
                    btnStart.BackColor = Color.Tomato;

                    lblStatus.Text = "请启动服务";
                    lblStatus.ForeColor = Color.Tomato;
                }
            }
            catch (HttpListenerException)
            {
                lblStatus.Text = $"端口{PORT}已经被占用";
                lblStatus.ForeColor = Color.Red;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        private void FrmMain_Load(object sender, EventArgs e)
        {
            App.DB.CodeFirst.IsAutoSyncStructure = true;
            App.WriteDefaultSetting();
        }

        private void tsAdd_Click(object sender, EventArgs e)
        {
            new FrmEditApi(null, () =>
            {
                ReLoadApi();
            }).ShowDialog();
        }

        private void tsEdit_Click(object sender, EventArgs e)
        {
            var selects = listViewApis.SelectedItems;
            if (selects.Count > 0)
            {
                var api = selects[0].Tag as Api;
                new FrmEditApi(api, () =>
                {
                    ReLoadApi();
                }).ShowDialog();
            }
        }

        private void tsCopyFullPath_Click(object sender, EventArgs e)
        {
            var selects = listViewApis.SelectedItems;
            if (selects.Count > 0)
            {
                var api = selects[0].Tag as Api;
                var fullPath = $"http://{IP}:{PORT}{api.Url}";
                Clipboard.SetText(fullPath);
            }
        }

        private void tsDelete_Click(object sender, EventArgs e)
        {
            var selects = listViewApis.SelectedItems;
            if (selects.Count > 0)
            {
                foreach (ListViewItem item in selects)
                {
                    var api = item.Tag as Api;
                    App.DB.Delete<Api>().Where(x => x.Id == api.Id).ExecuteAffrows();
                    listViewApis.Items.RemoveAt(item.Index); // 按索引移除  
                }
            }
        }


        private void ReLoadApi()
        {
            var apis = App.DB.Queryable<Api>().ToList();
            if (apis.Count > 0)
            {
                this.listViewApis.Items.Clear();
                this.listViewApis.BeginUpdate();

                foreach (Api api in apis)
                {
                    ListViewItem lvi = new ListViewItem();
                    //lvi.ImageIndex = i; 

                    lvi.Tag = api;
                    lvi.Text = api.Url;
                    lvi.SubItems.Add(api.Method);
                    lvi.SubItems.Add(api.Description);

                    this.listViewApis.Items.Add(lvi);
                }

                this.listViewApis.EndUpdate();
            }
        }

        private void InitializeListView()
        {
            listViewApis.FullRowSelect = true;
            listViewApis.View = View.Details;
            listViewApis.Columns.Add("HTTP 请求路径", 150, HorizontalAlignment.Left);//一步添加 
            listViewApis.Columns.Add("HTTP 请求方法", 100, HorizontalAlignment.Left); //一步添加  
            listViewApis.Columns.Add("描述", 320, HorizontalAlignment.Left); //一步添加  
        }

        #region 关于
        private void listViewApis_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tsEdit_Click(sender, e);
        }

        private void 开源地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(@"https://gitee.com/handloong/mockjson");
        }

        private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var softwareVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            MessageBox.Show($"MockJson - Api模拟器", $"MockJson [{softwareVersion}]", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private void 操作说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show($@"Ⅰ.您可以在列表中右键操作:新增，编辑，删除
Ⅱ.双击接口可以快速进入编辑界面
Ⅲ.右键复制全路径可以直接复制完整的接口路径
Ⅳ.在设置中可以设置您的一些操作习惯
", $"简单说明", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion

        #region 菜单
        private void tsSetting_Click(object sender, EventArgs e)
        {
            new FrmSetting(() =>
            {
                LoadUrl();
            }).ShowDialog();
        }

        private void LoadUrl()
        {
            var settings = App.DB.Queryable<Setting>().ToList();
            IP = App.GetValue("IP", "localhost", settings);
            PORT = App.GetValue("PORT", "8099", settings);
        }

        private void 重启软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void 退出软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

    }
}
